﻿using System;
using System.Web;
using System.Collections.Specialized;
using System.Web.Mvc;
using System.Web.Routing;
using Moq;
using System.Security.Principal;
using WeBlog.Models;
using System.Collections.Generic;

namespace WeBlog.Tests.Helpers
{
    public static class MvcMockHelpers
    {
        public static HttpContextBase FakeHttpContext(string url)
        {
            var context = MockContext();
            context.Object.Request.SetupRequestUrl(url);
            return context.Object;
        }

        //public static Mock<HttpContextBase> FakeHttpContext(IPrincipal principal = null)
        //{
        //    return MockContext(principal);
        //}

        public static Mock<HttpContextBase> MockContext()
        {
            var context = new Mock<HttpContextBase>();
            
            var request = new Mock<HttpRequestBase>();
            request.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection());
            request.Object.Cookies.Add(new HttpCookie("WeBlog-Votes"));    
        
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();            

            context.Setup(ctx => ctx.Request).Returns(request.Object);            
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Session).Returns(session.Object);
            context.Setup(ctx => ctx.Server).Returns(server.Object);            
            return context;
        }

        public static void SetFakeControllerContext(this Controller controller)
        {
            var httpContext = MockContext();
            var context = new ControllerContext(new RequestContext(httpContext.Object, new RouteData()), controller);
            controller.ControllerContext = context;
            controller.ValueProvider = new FormCollection().ToValueProvider();
            controller.Url = new UrlHelper( context.RequestContext, new RouteCollection() );            
        }

        public static void SetFakeControllerContext(this Controller controller, IPrincipal principal, User user )
        {
            var httpContext = MockContext();            
            httpContext.Setup(ctx => ctx.User).Returns(principal);
            httpContext.Setup(ctx => ctx.Session["User"]).Returns(user);

            var context = new ControllerContext(new RequestContext(httpContext.Object, new RouteData()), controller);
            controller.ControllerContext = context;
            controller.ValueProvider = new FormCollection().ToValueProvider();
            controller.Url = new UrlHelper(context.RequestContext, new RouteCollection());
        }

        static string GetUrlFileName(string url)
        {
            if (url.Contains("?"))
                return url.Substring(0, url.IndexOf("?"));
            return url;
        }

        static NameValueCollection GetQueryStringParameters(string url)
        {
            if (url.Contains("?"))
            {
                NameValueCollection parameters = new NameValueCollection();

                string[] parts = url.Split("?".ToCharArray());
                string[] keys = parts[1].Split("&".ToCharArray());

                foreach (string key in keys)
                {
                    string[] part = key.Split("=".ToCharArray());
                    parameters.Add(part[0], part[1]);
                }

                return parameters;
            }
            else
            {
                return null;
            }
        }

        public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod)
        {
            Mock.Get(request)
                .Setup(req => req.HttpMethod)
                .Returns(httpMethod);
        }

        public static void SetupRequestUrl(this HttpRequestBase request, string url)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            if (!url.StartsWith("~/"))
                throw new ArgumentException("Sorry, we expect a virtual url starting with \"~/\".");

            var mock = Mock.Get(request);

            mock.Setup(req => req.QueryString)
                .Returns(GetQueryStringParameters(url));
            mock.Setup(req => req.AppRelativeCurrentExecutionFilePath)
                .Returns(GetUrlFileName(url));
            mock.Setup(req => req.PathInfo)
                .Returns(string.Empty);
        }

        public static ValueProviderCollection SetupValueProvider(Dictionary<string, string> formValues)
        {
            var valueProviders = new List<IValueProvider>();
            var form = new FormCollection();

            if (formValues != null)
            {
                foreach (string key in formValues.Keys)
                {
                    form.Add(key, formValues[key]);
                }
            }

            valueProviders.Add(form);
            return new ValueProviderCollection(valueProviders);
        }
    }
}